# This file is part of Gehyra.
#
# Gehyra is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gehyra is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gehyra.  If not, see <http://www.gnu.org/licenses/>.

"""
@package gehyra.test.runner
Harness for running a subset of test suites from the gehyra
command line.
$Id: runner.py 454 2011-02-08 14:26:59Z andyhhp@gmail.com $
"""

"""
@file gehyra/test/runner
Harness for running a subset of test suites from the gehyra
command line.
"""

import os.path
import glob
import unittest

from gehyra.common.logger import LOG

def run_tests(test_list):
    """run test suites.
    This is called when the user specified -r on the gehyra command
    line.  It runs the specified test suites and presents the results
    in the standard fashon to stdout and stderr.
    @param test_list List of tests to run
    """

    base_dir, _ = os.path.split(__file__)

    def get_module_name(full_path):
        """get the module name from a full path"""
        (_, fn) = os.path.split(full_path)
        return fn.split('.', 1)[0]

    if 'all' in test_list:

        mods = map(get_module_name, glob.iglob(base_dir + "/test_*.py"))

    else:
        
        mods = map(get_module_name,
                    filter(os.path.exists,
                            (os.path.join(base_dir, "test_%s.py" % y)
                             for y in test_list)))
        

    LOG.debug("Attempting to run test suites %s" % mods)

    dtl = unittest.defaultTestLoader

    ml = [ "gehyra.test.%s" % x for x in mods ]

    def check_ok(mod):
        """Attempt to import and check that no errors occur.
        This is because TestLoader.loadTestsFromNames does not
        deal with it correctly.
        """
        try:
            __import__(mod)
        except Exception as e:
            LOG.warning("Exception when loading "
                        "test suite %s: %s" % (mod, e))
            return False
        return True

    vml = filter(check_ok, ml)

    if len(ml) != len(vml):
        LOG.debug("Running test suites %s" % vml)

    runner = unittest.TextTestRunner()

    runner.run(dtl.loadTestsFromNames(vml))
    


